package com.se7en.ufutil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.R.integer;
import java.lang.Integer;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.ArrayAdapter;

import com.google.android.maps.GeoPoint;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;


public class DataAccess {
	private Context context;
	private static SQLiteDatabase database;
	private Cursor trashcursor;
	private static Cursor roomcursor;
	private Cursor parkingcursor;

	public DataAccess(Context context) {
		this.context = context;
	}

	public DataAccess open() throws SQLException {
		try {
			DatabaseHelper.createDatabaseIfNotExists(context);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(database == null)
			database = DatabaseHelper.getStaticDb();
		return this;
	}

	public void close() {
		if(database != null) database.close();
	}

	// Adlai: Always a good idea to start with an ArrayList
	// until the size of the data set is known.
	public TrashModel[] getAllTrashModels()
	{
		ArrayList<TrashModel> ret = new ArrayList<TrashModel>();
		trashcursor = database.query("trash", null, null, null, null,
				null, null);
		trashcursor.moveToFirst();
		while (trashcursor.isAfterLast() == false) {
        	TrashModel.TrashType type = TrashModel.TrashType.TRASH;
        	
        	if (trashcursor.getInt(3)==2) {
        		type = TrashModel.TrashType.RECYCLE_PLASTIC;
        	}
        	
        	else if (trashcursor.getInt(3)==2) {
        		type = TrashModel.TrashType.RECYCLE_PAPER;
        	}
        	ret.add(new TrashModel(new GeoPoint(trashcursor.getInt(1), trashcursor.getInt(2)), type));
            trashcursor.moveToNext();
        }
		trashcursor.close();
		// Adlai: A bit odd to put new TrashModel[0]
		// in there, but it feels less filthy than casting.
		return ret.toArray(new TrashModel[0]);
	}
	public StudyAreaModel[] getStudyLocs() {
		ArrayList<StudyAreaModel> studs = new ArrayList<StudyAreaModel>();
		studs.add(new StudyAreaModel(0,new GeoPoint(29647953,-82343941),"Marston Library","M-Th 8am - 1am, F 8am - 10pm, Sa 10am - 6pm, Su 10am - 1am"));
		studs.add(new StudyAreaModel(1,new GeoPoint(29648344,-82344348),"CSE Dungeon","Forever"));
		studs.add(new StudyAreaModel(2,new GeoPoint(29651342,-82342937),"Library West","M-Th 8am - 1am, F 8am - 10pm, Sa 10am - 6pm, Su 10am - 1am"));
		studs.add(new StudyAreaModel(3,new GeoPoint(29636198,-82370312),"Herbarium","M-F 8am - 5pm, Sa closed, Su closed"));
		studs.add(new StudyAreaModel(4,new GeoPoint(29649775,-82359170),"Law Library","M-Th 7:30am - 11:30am, F 7:30am - 7:30pm, Sa 10:00am - 6:00pm, Su 10:00am - 11:30pm"));
		studs.add(new StudyAreaModel(5,new GeoPoint(29646456,-82347722),"The Reitz","Su-Th 7am - 3am, F-Sa 7am - 1:30am"));
		studs.add(new StudyAreaModel(6,new GeoPoint(29648209,-82345555),"The Hub","M-Th 7:30am - 10:00pm, F 7:30am - 5pm, Sa-Su 12am - 6pm"));
		studs.add(new StudyAreaModel(7,new GeoPoint(29646503,-82342036),"Broward Teaching Center","M 8am - 5pm, Tu 8am - 7pm, W 8am - 5pm, Th 8am - 7pm, F 8am - 5pm, Su 6pm - 9pm"));
		studs.add(new StudyAreaModel(8,new GeoPoint(29650876,-82341853),"Smathers Library","M-Th 9am - 6pm, F 9am - 5pm, Sa closed, Su closed"));
		studs.add(new StudyAreaModel(9,new GeoPoint(29648190,-82340587),"Architecture & Fine Arts Library","M-Th 8am - 10pm, F 8am - 5pm, Sa 1pm - 5pm, Su 2pm - 10pm"));
		studs.add(new StudyAreaModel(10,new GeoPoint(29646792,-82338152),"Education Library","M-Th 8am - 10pm, F 8am - 8pm, Sa 10am - 6pm, Su 10am - 10pm"));
		studs.add(new StudyAreaModel(11,new GeoPoint(29647761,-82347400),"Journalism Library","M-Th 8am - 8pm, F 8am - 5pm, Sa closed, Su closed"));
		studs.add(new StudyAreaModel(12,new GeoPoint(29648209,-82342991),"Music Library","M-Th 8am - 8pm, F 8am - 5pm, Sa closed, Su noon - 8pm"));
		return studs.toArray(new StudyAreaModel[0]);
		
	}
	
	public static int getStudyID(String n) {
		if (n.equals("Marston Library")) return 0;
		else if (n.equals("CSE Dungeon")) return 1;
		else if (n.equals("Library West")) return 2;
		else if (n.equals("Law Library")) return 4;
		else if (n.equals("The Reitz")) return 5;
		else if (n.equals("The Hub")) return 6;
		else if (n.equals("Broward Teaching Center")) return 7;
		else if (n.equals("Herbarium")) return 3;
		else if (n.equals("Smathers Library")) return 8;
		else if (n.equals("Architecture & Fine Arts Library")) return 9;
		else if (n.equals("Education Library")) return 10;
		else if (n.equals("Journalism Library")) return 11;
		else if (n.equals("Music Library")) return 12;
		else return 0;
	}
	
	public static void postComment(int id, String comment, String deviceID) {
    	RequestParams params = new RequestParams();
    	params.put("id", Integer.toString(id));
    	params.put("text", comment);
        myHttpClient.post("comments.php?action=post", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                //Log.i("Justin",response);
            }
        });
	} 
	
    public static void postRating(int id, String guid, float d, float f, float g) {
    	RequestParams params = new RequestParams();
    	params.put("id", Integer.toString(id));
    	params.put("guid", guid);
    	params.put("o", Float.toString(d));
    	params.put("q", Float.toString(f));
    	params.put("c", Float.toString(g));
        myHttpClient.post("comments.php?action=rate", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(String response) {
                //Log.i("Justin",response);
            }
        });
    }
	
	public static float[] getRating(int id) {
		//index 0=overall
		//		1=quietness
		//		2=crowdedness
		String url ="http://theatrestrikeforce.org/uf/comments.php?action=fetchr&sa="+Integer.toString(id);
		URI uri = null;
		try {
			uri = new URI(url);
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		HttpPost post = new HttpPost(uri);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		try {
			response = client.execute(post);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String json = null;
		try {
			json = reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONTokener tokener = new JSONTokener(json);
		JSONArray finalResult = null;
		try {
			finalResult = new JSONArray(tokener);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject jsonObject = null;
		try {
			jsonObject = finalResult.getJSONObject(0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		float[] ret = new float[3];
        try {
			ret[0]=(float) jsonObject.getDouble("o");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        try {
			ret[1]=(float) jsonObject.getDouble("q");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        try {
			ret[2]=(float) jsonObject.getDouble("c");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
					
        return ret;
	}
	
	public static StudyComment[] getComments(int id) {
		StudyComment temp = null;
		//String[i][0]=comment i
		//String[i][1]=time of comment i (as string)
		String url = "http://theatrestrikeforce.org/uf/comments.php?action=fetch&sa="+Integer.toString(id);
		URI uri = null;
		try {
			uri = new URI(url);
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		HttpPost post = new HttpPost(uri);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		try {
			response = client.execute(post);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String json = null;
		try {
			json = reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONTokener tokener = new JSONTokener(json);
		JSONArray finalResult = null;
		try {
			finalResult = new JSONArray(tokener);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<StudyComment> ret = new ArrayList<StudyComment>();
		for (int i=0; i<finalResult.length(); i++){
			JSONObject jsonObject = null;
			String item = null;
			try {
				jsonObject = finalResult.getJSONObject(i);
				//item=jsonObject.getString("text")+ "-_-" + jsonObject.getString("time");
				temp = new StudyComment(jsonObject.getString("time"),jsonObject.getString("text"));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			ret.add(temp);
		}
			
        return ret.toArray(new StudyComment[0]);
	}
	
	public FloorModel[] getAllClasses()
	{
		ArrayList<FloorModel> ret = new ArrayList<FloorModel>();
		ret.add(new FloorModel(0,new GeoPoint(29648088, -82344074),"CISE",3));
		ret.add(new FloorModel(1,new GeoPoint(29649165, -82344096), "Turlington",4));
		ret.add(new FloorModel(2,new GeoPoint(29649328, -82347255), "FLA Gym",3));
		// Paul: casting didn't work
		return ret.toArray(new FloorModel[0]);
	}
	
	public static ArrayAdapter<CharSequence> getBldgAdapter(Context mcontext) {
		ArrayAdapter <CharSequence> adapter =
				  new ArrayAdapter <CharSequence> (mcontext, android.R.layout.simple_spinner_item );
				adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		adapter.add("CISE");
		adapter.add("Turlington");
		adapter.add("FLA Gym");
		return adapter;
	}
	
	public static int getFloors(String bldg) {
		if (bldg.equals("CISE")) return 5;
		else if (bldg.equals("Turlington")) return 2;
		else if (bldg.equals("FLA Gym")) return 3;
		else return 1;
	}
	
	public static int[] getRoomLocation(String roomnum, String bldg) {
		int[] ret=new int[] {0,0,0};

		roomcursor = database.query("rooms", null, "roomno='"+roomnum+"' and bldg='"+bldg+"'", null, null, null, null);
		if (roomcursor.getCount()==0) {
			ret[0]=-1;
			return ret;
		}
		roomcursor.moveToFirst();      	
        ret[0]=roomcursor.getInt(4);
        ret[1]=roomcursor.getInt(5);
        ret[2]=roomcursor.getInt(2);
        roomcursor.close();
        //Log.i("justin",Integer.toString(ret[0])+" "+Integer.toString(ret[1]));
        return ret;
		
	}
	
	public static Object[] getRestrooms(String bldg, int floor, String gender) {
		ArrayList<Object> ret = new ArrayList<Object>();
		roomcursor = database.rawQuery("SELECT * FROM rooms WHERE bldg='"+bldg+"' and floor='"+floor+"' and roomno='"+gender+"'", null);
		if (roomcursor.getCount()==0) {
			Object[] retu= new Object[] {-1};
			return retu;

		}
		roomcursor.moveToFirst();
        while (roomcursor.isAfterLast() == false) {
        	ret.add(roomcursor.getInt(4));
        	ret.add(roomcursor.getInt(5));
        	roomcursor.moveToNext();
        }
        roomcursor.close();
        //Log.i("justin",Integer.toString(ret[0])+" "+Integer.toString(ret[1]));
        return ret.toArray(new Object[0]);
		
	}
	
	
	public DiningModel[] getAllDining()
	{
		ArrayList<DiningModel> ret = new ArrayList<DiningModel>();
		Cursor diningcursor = database.query("dining", null, null, null, null,
				null, null);
		diningcursor.moveToFirst();
        while (diningcursor.isAfterLast() == false) {
        	DiningModel.DiningType type = DiningModel.DiningType.RESTAURANT;
        	if (diningcursor.getInt(7)==1) {
        		type = DiningModel.DiningType.DINING_HALL;
        	}

        	ret.add(new DiningModel(new GeoPoint(diningcursor.getInt(1),diningcursor.getInt(2)), type, diningcursor.getString(5), diningcursor.getString(4), diningcursor.getString(6), diningcursor.getString(3)));
            diningcursor.moveToNext();
        }
        diningcursor.close();
		return ret.toArray(new DiningModel[0]);
	}
	
	/* OLD getDiningMeals() function
	
	public static String[] getDiningMeals(int source, String day, boolean update) {
		//source = 0 for FFC and 1 for GC
		//Day = "Monday","Tuesday",...
		//No caching implemented yet
		String[] url = new String[] {"http://theatrestrikeforce.org/uf/ffc.json","http://theatrestrikeforce.org/uf/gc.json"};
		URI uri = null;
		try {
			uri = new URI(url[source]);
		} catch (URISyntaxException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		HttpPost post = new HttpPost(uri);
		HttpClient client = new DefaultHttpClient();
		HttpResponse response = null;
		try {
			response = client.execute(post);
		} catch (ClientProtocolException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String json = null;
		try {
			json = reader.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONTokener tokener = new JSONTokener(json);
		JSONObject finalResult = null;
		try {
			finalResult = new JSONObject(tokener);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		JSONArray jsonObject = null;
		try {
			jsonObject = finalResult.getJSONArray(day);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ArrayList<String> ret = new ArrayList<String>();
        for (int i = 0; i < jsonObject.length(); i++) {
              try {
				ret.add(jsonObject.getJSONArray(i).getString(0));
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        }
			
        return ret.toArray(new String[0]);
	} end old getDiningMeals() */
	
	public ParkingModel[] getAllParking()
	{
		ArrayList<ParkingModel> ret = new ArrayList<ParkingModel>();
		parkingcursor = database.query("parking", null, null, null, null,
				null, null);
		parkingcursor.moveToFirst();
        while (parkingcursor.isAfterLast() == false) {
        	ParkingModel.ParkingType type;
    		
        switch (parkingcursor.getInt(3)) {
  		  case 0: 
  		    type=ParkingModel.ParkingType.RED_1;
  		    break;
  		  case 1: 
  		    type=ParkingModel.ParkingType.ORANGE;
  		    break;
  		  case 2: 
  		    type=ParkingModel.ParkingType.GATED;
  		    break;
  		  case 3: 
  		    type=ParkingModel.ParkingType.RESERVED;
  		    break;
  		  case 4: 
  		    type=ParkingModel.ParkingType.CARPOOL;
  		    break;
  		  case 5:
  			type=ParkingModel.ParkingType.GREEN;
  			break;
  		  default: 
  		    type=ParkingModel.ParkingType.SCOOTER;
        }
  		  ret.add(new ParkingModel(new GeoPoint(parkingcursor.getInt(1), parkingcursor.getInt(2)), type, parkingcursor.getString(4), parkingcursor.getString(5)));
            parkingcursor.moveToNext();
		}
        parkingcursor.close();
		return ret.toArray(new ParkingModel[0]);
	}
}
